import 'dart:io';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_alarm/flutter_alarm.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = '未知';
  List<AlarmInfo> _alarms = [];
  bool _permissionsGranted = false;
  final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();

  @override
  void initState() {
    super.initState();
    initPlatformState();
    checkPermissions();
    loadAlarms();
  }

  // 初始化平台信息
  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = await FlutterAlarm.platformVersion;
    } on PlatformException {
      platformVersion = '获取平台版本失败';
    }

    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  // 检查权限
  Future<void> checkPermissions() async {
    bool granted = await FlutterAlarm.checkPermission();
    setState(() {
      _permissionsGranted = granted;
    });
  }

  // 请求权限
  Future<void> requestPermissions() async {
    bool granted = await FlutterAlarm.requestPermission();
    setState(() {
      _permissionsGranted = granted;
    });
    if (!granted) {
      _showPermissionsErrorDialog('权限请求被拒绝，部分功能可能无法正常使用。');
    }
  }

  // 加载闹钟列表
  Future<void> loadAlarms() async {
    try {
      var result = await FlutterAlarm.getAllAlarms();
      if (result.status) {
        setState(() {
          _alarms = result.data;
        });
      } else {
        _showErrorDialog(result.msg);
      }
    } catch (e) {
      print('加载闹钟失败: $e');
    }
  }

  // 设置重复闹钟
  Future<void> _setupCheckInReminders1() async {
    if (!_permissionsGranted) {
      await requestPermissions();
      if (!_permissionsGranted) {
        return;
      }
    }
    DateTime now = DateTime.now();
    DateTime nextMinute = now.add(Duration(minutes: 1));
    int hour = nextMinute.hour;
    int minute = nextMinute.minute;
    var result = await FlutterAlarm.setRepeatingAlarm("checkin_1", "checkin",
        hour, minute, "签到提醒", "亲，别忘了${_formatTime(hour, minute)}签到哦！");
    if (result.status) {
      _showSuccessDialog('签到提醒设置成功！\n将在每日${_formatTime(hour, minute)}提醒您签到。');
    } else {
      _showErrorDialog(result.msg);
    }
    loadAlarms();
  }

  Future<void> _setupCheckInReminders2() async {
    if (!_permissionsGranted) {
      await requestPermissions();
      if (!_permissionsGranted) {
        return;
      }
    }
    DateTime now = DateTime.now();
    DateTime nextMinute = now.add(Duration(minutes: 5));
    int hour = nextMinute.hour;
    int minute = nextMinute.minute;
    var result = await FlutterAlarm.setRepeatingAlarm("checkin_2", "checkin",
        hour, minute, "签到提醒", "亲，别忘了${_formatTime(hour, minute)}签到哦！");
    if (result.status) {
      _showSuccessDialog('签到提醒设置成功！\n将在每日${_formatTime(hour, minute)}提醒您签到。');
    } else {
      _showErrorDialog(result.msg);
    }
    loadAlarms();
  }

  Future<void> _setupSingleReminder1() async {
    if (!_permissionsGranted) {
      await requestPermissions();
      if (!_permissionsGranted) {
        return;
      }
    }
    DateTime now = DateTime.now();
    DateTime nextMinute = now.add(Duration(minutes: 2));
    int hour = nextMinute.hour;
    int minute = nextMinute.minute;
    // 获取当前日期，格式为yyyy-MM-dd
    String date =
        "${now.year.toString().padLeft(4, '0')}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}";
    var result = await FlutterAlarm.setAlarm("single_1", "single", date, hour,
        minute, "单次提醒", "亲，单次提醒${_formatTime(hour, minute, date)}！");
    if (result.status) {
      _showSuccessDialog('单次提醒设置成功！\n将在${_formatTime(hour, minute, date)}提醒您。');
    } else {
      _showErrorDialog(result.msg);
    }
    loadAlarms();
  }

  Future<void> _loadSingleReminder1() async {
    var result = await FlutterAlarm.getAlarmByAlarmId("single_1", "single");
    if (result.status) {
      setState(() {
        _alarms = result.data != null ? [result.data] : [];
      });
    } else {
      _showErrorDialog(result.msg);
    }
  }

  Future<void> _loadCheckinReminders() async {
    var result = await FlutterAlarm.getAlarmsByTag("checkin");
    if (result.status) {
      setState(() {
        _alarms = result.data;
      });
    } else {
      _showErrorDialog(result.msg);
    }
  }

  // 取消所有提醒
  Future<void> _cancelAllReminders() async {
    var result = await FlutterAlarm.cancelAllAlarms();
    if (result.status) {
      _showSuccessDialog(result.msg);
      loadAlarms();
    } else {
      _showErrorDialog(result.msg);
    }
  }

  Future<void> _cancelRemindersByTag(String tag) async {
    var result = await FlutterAlarm.cancelAlarmsByTag(tag);
    if (result.status) {
      _showSuccessDialog(result.msg);
      loadAlarms();
    } else {
      _showErrorDialog(result.msg);
    }
  }

  // 取消单个提醒
  Future<void> _cancelAlarm(String tag, String alarmId) async {
    var result = await FlutterAlarm.cancelAlarm(alarmId, tag);
    if (result.status) {
      _showSuccessDialog(result.msg);
      loadAlarms();
    } else {
      _showErrorDialog(result.msg);
    }
  }

  // 显示成功对话框
  void _showSuccessDialog(String message) {
    final BuildContext dialogContext = _navigatorKey.currentContext ?? context;
    showDialog(
      context: dialogContext,
      builder: (context) => AlertDialog(
        title: Text('成功'),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  // 显示错误对话框
  void _showErrorDialog(String message) {
    final BuildContext dialogContext = _navigatorKey.currentContext ?? context;
    showDialog(
      context: dialogContext,
      builder: (context) => AlertDialog(
        title: Text('错误'),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  // 显示错误对话框
  void _showPermissionsErrorDialog(String message) {
    final BuildContext dialogContext = _navigatorKey.currentContext ?? context;
    showDialog(
      context: dialogContext,
      builder: (context) => AlertDialog(
        title: Text('错误'),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('确定'),
          ),
          SizedBox(width: 20),
          if (Platform.isIOS)
            TextButton(
              onPressed: () {
                FlutterAlarm.settingPermission();
                Navigator.of(context).pop();
              },
              child: Text('去设置'),
            ),
        ],
      ),
    );
  }

  // 格式化时间显示
  String _formatTime(int hour, int minute, [String date]) {
    return '${date == null ? "" : "$date "}${hour.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: _navigatorKey,
      title: '闹钟提醒示例',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('闹钟提醒示例'),
          backgroundColor: Colors.blue,
        ),
        body: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 平台信息
              Card(
                child: Padding(
                  padding: EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('平台信息',
                          style: TextStyle(
                              fontSize: 18, fontWeight: FontWeight.bold)),
                      SizedBox(height: 8),
                      Text('运行在: $_platformVersion'),
                      Text('权限状态: ${_permissionsGranted ? '已授权' : '未授权'}'),
                    ],
                  ),
                ),
              ),

              SizedBox(height: 16),

              // 操作按钮
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      onPressed: _setupCheckInReminders1,
                      child: Text('设置签到提醒1'),
                      style: ElevatedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 12),
                      ),
                    ),
                  ),
                  SizedBox(width: 8),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: _cancelAllReminders,
                      child: Text('取消所有提醒'),
                      style: ElevatedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 12),
                      ),
                    ),
                  ),
                ],
              ),

              SizedBox(height: 16),

              // 操作按钮
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      onPressed: _setupCheckInReminders2,
                      child: Text('设置签到提醒2'),
                      style: ElevatedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 12),
                      ),
                    ),
                  ),
                  SizedBox(width: 8),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () => _cancelRemindersByTag("checkin"),
                      child: Text('删除签到提醒'),
                      style: ElevatedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 12),
                      ),
                    ),
                  ),
                ],
              ),

              SizedBox(height: 16),

              // 操作按钮
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      onPressed: _setupSingleReminder1,
                      child: Text('设置单次提醒'),
                      style: ElevatedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 12),
                      ),
                    ),
                  ),
                  SizedBox(width: 8),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: _loadSingleReminder1,
                      child: Text('获取单次提醒'),
                      style: ElevatedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 12),
                      ),
                    ),
                  ),
                ],
              ),

              SizedBox(height: 16),

              // 操作按钮
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      onPressed: _loadCheckinReminders,
                      child: Text('获取签到提醒'),
                      style: ElevatedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 12),
                      ),
                    ),
                  ),
                  SizedBox(width: 8),
                  Expanded(
                    child: SizedBox(),
                  ),
                ],
              ),

              SizedBox(height: 24),

              // 闹钟列表
              Text('已设置的提醒',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
              SizedBox(height: 8),

              Expanded(
                child: _alarms.isEmpty
                    ? Center(
                        child: Text(
                          '暂无提醒\n\n点击“设置签到提醒”按钮来创建您的第一个提醒',
                          textAlign: TextAlign.center,
                          style: TextStyle(color: Colors.grey, fontSize: 16),
                        ),
                      )
                    : ListView.builder(
                        itemCount: _alarms.length,
                        itemBuilder: (context, index) {
                          final alarm = _alarms[index];
                          return Card(
                            child: ListTile(
                              leading: Icon(
                                alarm.repeating ? Icons.repeat : Icons.schedule,
                                color: Colors.blue,
                              ),
                              title: Text(alarm.title),
                              subtitle: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(alarm.body),
                                  Text(
                                    alarm.repeating
                                        ? '每日 ${_formatTime(alarm.hour ?? 0, alarm.minute ?? 0)}'
                                        : _formatTime(alarm.hour, alarm.minute,
                                            alarm.date),
                                    style: TextStyle(
                                        fontSize: 12, color: Colors.grey[600]),
                                  ),
                                ],
                              ),
                              trailing: IconButton(
                                icon: Icon(Icons.delete, color: Colors.red),
                                onPressed: () =>
                                    _cancelAlarm(alarm.tag, alarm.alarmId),
                              ),
                            ),
                          );
                        },
                      ),
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: loadAlarms,
          child: Icon(Icons.refresh),
          tooltip: '刷新提醒列表',
        ),
      ),
    );
  }
}
